package com.yndsoft.jc.ui.memberpage.personal;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yndsoft.jc.R;
import com.yndsoft.jc.activity.BaseActivity;
import com.yndsoft.jc.model.Member;
import com.yndsoft.jc.model.ReturnMsg;
import com.yndsoft.jc.netutils.AppUtils;
import com.yndsoft.jc.supplier.join.PopupWindowAddress;
import com.yndsoft.jc.supplier.utils.ToastUtil;
import com.yndsoft.jc.supplier.widget.dialog.SupplierDialog;
import com.yndsoft.jc.supplier.widget.popupwindow.OnChooseDataListener;
import com.yndsoft.jc.ui.net.util.ProgressSubscriber;
import com.yndsoft.jc.utils.ConstantValues;
import com.yndsoft.jc.utils.permission.CheckPermission;
import com.yndsoft.jc.utils.permission.PermissionActivity;
import com.yndsoft.jc.utils.selectphoto.SelectPhotoActivity;
import com.yndsoft.jc.widget.CircleImageView;

import java.lang.reflect.Type;

import butterknife.Bind;

import static com.yndsoft.jc.utils.ConstantValues.PERMISSION_GRANTED;
import static com.yndsoft.jc.utils.ConstantValues.REQUEST_CODE;

public class PersonalInfoActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.person_info_parent)
    LinearLayout person_info_parent;//最外层父布局
    @Bind(R.id.base_backBtn)
    RelativeLayout base_backBtn;
    @Bind(R.id.base_title)
    TextView base_title;

    @Bind(R.id.person_info_pic)
    CircleImageView person_info_pic;
    @Bind(R.id.personal_cell)
    TextView personal_cell;
    @Bind(R.id.personal_codeno)
    TextView personal_codeno;

    @Bind(R.id.person_phone)
    EditText person_phone;
    @Bind(R.id.person_email)
    EditText person_email;
    @Bind(R.id.person_addrs)
    TextView person_addrs;
    @Bind(R.id.person_nickName)
    EditText person_nickName;
    @Bind(R.id.person_realName)
    EditText person_realName;

    @Bind(R.id.rl_choose_pic)
    RelativeLayout rl_choose_pic;
    @Bind(R.id.person_sex_change)
    RelativeLayout person_sex_change;//性别选择
    @Bind(R.id.person_site_change)
    RelativeLayout person_site_change;
    @Bind(R.id.person_info_sex)
    TextView person_info_sex;
    @Bind(R.id.person_info_commit)
    Button person_info_commit;
    //自定义的弹出框类
//    SelectPicPopupWindow menuWindow;

    private int provinceKey = 0;
    private String provinceValue = "";
    private int cityKey = 0;
    private String cityValue = "";
    private int districtKey = 0;
    private String districtValue = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        checkPermission = CheckPermission.getInstance(this);

        setViews();
        getDatas();
        setListener();
    }

    private void getDatas() {
        mHttpUtil.getPersonInfo(new ProgressSubscriber<ReturnMsg>(mContext) {
            @Override
            public void next(ReturnMsg returnMsg) {

                switch (returnMsg.getCode()) {
                    case 0:

                        break;
                    case 1:
                        Type type = new TypeToken<Member>() {}.getType();
                        Object fromJson = new Gson().fromJson(returnMsg.getInfo(), type);
                        Member member = (Member) fromJson;
                        if (!TextUtils.isEmpty(member.getImg()) && member.getImg().indexOf("/pic/") != -1) {
                            String imgUrl = member.getImg().replace("/pic/", "http://111.231.140.198:9091/");
                            Glide.with(mContext).load(imgUrl).into(person_info_pic);
                        }
                        AppUtils.setText(personal_cell, member.getPhone());
                        AppUtils.setText(personal_codeno, "推荐码：" + member.getCodeno());
                        if (member.getSex() != null) {
                            if (member.getSex() == 0) {
                                AppUtils.setText(person_info_sex, "保密");
                            } else if (member.getSex() == 1) {
                                AppUtils.setText(person_info_sex, "男");
                            } else if (member.getSex() == 2) {
                                AppUtils.setText(person_info_sex, "女");
                            }
                        } else {
                            AppUtils.setText(person_info_sex, "");
                        }
                        AppUtils.setText(person_phone, member.getPhone());
                        AppUtils.setText(person_email, member.getEmail());

                        if (member.getProvince() != null && member.getCity() != null && member.getDistrict() != null) {
                            provinceKey = member.getProvinceid();
                            provinceValue = member.getProvince();
                            cityKey = member.getCityid();
                            cityValue = member.getCity();
                            districtKey = member.getDistrictid();
                            districtValue = member.getDistrict();
                        }
                        AppUtils.setText(person_addrs, (member.getProvince() + " " + member.getCity() + " " + member.getDistrict()));

                        AppUtils.setText(person_nickName, member.getName());
                        AppUtils.setText(person_realName, member.getTruename());

                        break;
                }
            }
        }, "member", mSession.getUserInfo().getId());
    }

    private void setViews() {
        base_title.setText(getResources().getString(R.string.personal_info));
    }

    private void setListener() {
        base_backBtn.setOnClickListener(this);
        person_sex_change.setOnClickListener(this);
        person_info_commit.setOnClickListener(this);
        rl_choose_pic.setOnClickListener(this);
        person_site_change.setOnClickListener(this);
    }


    private BottomMenu menuWindow;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.base_backBtn:
                finish();
                break;
            case R.id.person_sex_change:
//                POPTYPE = 0;
//                initPopupSexOrPhoto(POPTYPE);
                //实例化SelectPicPopupWindow
//                menuWindow = new SelectPicPopupWindow(PersonalInfoActivity.this, itemsOnClick);
//                //显示窗口
//                menuWindow.showAtLocation(person_info_parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                menuWindow = new BottomMenu(PersonalInfoActivity.this, clickListener);
                menuWindow.show();
                break;
            case R.id.person_info_commit:
                if (TextUtils.isEmpty(person_email.getText()) || !isEmail(person_email.getText().toString())) {
                    showHint("邮箱不正确");
                } else {
                    if (TextUtils.isEmpty(person_nickName.getText())) {
                        showHint("昵称不能为空");
                    } else {
                        if (TextUtils.isEmpty(person_realName.getText())) {
                            showHint("真实姓名不能为空");
                        } else {
                            commitPersonInfo();
                        }
                    }
                }
                break;
            case R.id.rl_choose_pic:
                if (checkPermission.permissionSet(ConstantValues.PERMISSION_COMMENT)) {
                    startPermissionActivity();
                } else {
                    Intent intentPhoto = new Intent(this, SelectPhotoActivity.class);
                    intentPhoto.putExtra("IsSingle", true);
                    startActivityForResult(intentPhoto, ConstantValues.USERHEDER);
                }
                break;
            case R.id.person_site_change:
                PopupWindowAddress address = new PopupWindowAddress(mContext, person_addrs.getText().toString());
                address.showAtLocation(person_info_parent, Gravity.BOTTOM, 0, 0);
                address.setOnChooseDataListener(new OnChooseDataListener() {
                    @Override
                    public void onChooseData(int key1, String value1, int key2, String value2, int key3, String value3) {
                        person_addrs.setText(value1 + " " + value2 + " " + value3);
                        person_addrs.setTextColor(0xFF333333);
                        provinceKey = key1;
                        provinceValue = value1;
                        cityKey = key2;
                        cityValue = value2;
                        districtKey = key3;
                        districtValue = value3;
                    }
                });
                break;
        }
    }

    private void commitPersonInfo() {
        Member member = new Member();
        member.setId(mSession.getUserInfo().getId());
        member.setPhone(personal_cell.getText().toString().trim());
        member.setCodeno(personal_codeno.getText().toString());
        if (person_info_sex.getText().equals("男")) {
            member.setSex(1);
        } else if (person_info_sex.getText().equals("女")) {
            member.setSex(2);
        } else {
            member.setSex(0);
        }
        member.setEmail(person_email.getText().toString());
//        member.setNote(person_addrs.getText().toString());
        member.setProvinceid(provinceKey);
        member.setProvince(provinceValue);
        member.setCityid(cityKey);
        member.setCity(cityValue);
        member.setDistrictid(districtKey);
        member.setDistrict(districtValue);
        member.setName(person_nickName.getText().toString());
        member.setTruename(person_realName.getText().toString());
        mHttpUtil.commitPersonInfo(new ProgressSubscriber<ReturnMsg>(mContext) {
            @Override
            public void next(ReturnMsg returnMsg) {
                switch (returnMsg.getCode()) {
                    case 0:
                        ToastUtil.show(mContext, "提交失败");
                        break;
                    case 1:
                        ToastUtil.show(mContext, "提交成功");
                        finish();
                        break;
                }
            }
        }, "update", new Gson().toJson(member));
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {

        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_man:
                    person_info_sex.setText("男");
                    break;
                case R.id.tv_male:
                    person_info_sex.setText("女");
                    break;
                default:
                    break;
            }
        }
    };

    private void showHint(String content) {
        new SupplierDialog(mContext).show(false, "提示", content);
    }

    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }

    private CheckPermission checkPermission;//检测权限器

    //进入权限设置页面
    private void startPermissionActivity() {
        PermissionActivity.startActivityForResult(this, REQUEST_CODE, ConstantValues.PERMISSION_COMMENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == ConstantValues.USERHEDER) {
                Glide.with(mContext).load(data.getStringExtra("mImgUrl")).into(person_info_pic);
//                Bitmap mBitmap = BitmapFactory.decodeStream(
//                        getContentResolver().openInputStream(data.getStringExtra("mImgUrl")));
            } else if (requestCode == PERMISSION_GRANTED) {
                Intent intent = new Intent(this, SelectPhotoActivity.class);
                startActivityForResult(intent, ConstantValues.USERHEDER);
            }
        } else if (resultCode == PermissionActivity.PERMISSION_GRANTED) {
            Intent intentPhoto = new Intent(this, SelectPhotoActivity.class);
            intentPhoto.putExtra("IsSingle", true);
            startActivityForResult(intentPhoto, ConstantValues.USERHEDER);
        }
    }
}
